package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.config.Result;
import com.example.service.LogService;
import com.example.service.UserService;
import com.example.pojo.MsslyyUser;
import com.example.service.MsslyyUserService;
import com.example.pojo.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/msslyyUser")
@Api(tags = "前台用户表")
public class MsslyyUserController {
    @Resource
    private MsslyyUserService msslyyUserService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;

    /**
     * 登录
     *
     * @param msslyyUser
     * @return
     */
    @ApiOperation(value = "前台用户登录",notes = "")
    @PostMapping("/login")
    public Result<MsslyyUser> login(@RequestBody MsslyyUser msslyyUser) {
        MsslyyUser res = msslyyUserService.login(msslyyUser);
        // 生成token
        String token = JWT.create().withAudience(res.getUserUsername()).sign(Algorithm.HMAC256(res.getUserPassword()));
        res.setToken(token);

        logService.log(msslyyUser.getUserUsername(), StrUtil.format("用户 {} 登录书店", msslyyUser.getUserUsername()));
        return Result.success(res);
    }

    /**
     * 注册
     *
     * @param msslyyUser
     * @param request
     * @return
     */
    @ApiOperation(value = "前台用户注册",notes = "")
    @PostMapping("/register")
    public Result<MsslyyUser> register(@RequestBody MsslyyUser msslyyUser, HttpServletRequest request) {
        if (msslyyUser.getUserPassword() == null) {
            msslyyUser.setUserPassword("123456");
        }
        MsslyyUser dbUser = msslyyUserService.register(msslyyUser);
        request.getSession().setAttribute("user1", msslyyUser);
        logService.log(msslyyUser.getUserUsername(), StrUtil.format("用户 {} 注册账号成功", msslyyUser.getUserUsername()));
        return Result.success(dbUser);
    }

    @GetMapping("/total")
    public Result<?> getTotal() {
        return Result.success(msslyyUserService.count());
    }

    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @ApiOperation(value = "新增前台用户",notes = "")
    @PostMapping
    public Result<?> save(@RequestBody MsslyyUser msslyyUser) {
        msslyyUserService.save(msslyyUser);
        return Result.success();
    }

    @ApiOperation(value = "更新前台用户",notes = "")
    @PutMapping
    public Result<?> update(@RequestBody MsslyyUser msslyyUser) {
        msslyyUserService.updateById(msslyyUser);
        return Result.success();
    }

    @ApiOperation(value = "删除前台用户",notes = "")
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        msslyyUserService.removeById(id);
        return Result.success();
    }

    @ApiOperation(value = "根据id查询",notes = "")
    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(msslyyUserService.getById(id));
    }

    @ApiOperation(value = "查询全部",notes = "")
    @GetMapping
    public Result<?> findAll() {
        List<MsslyyUser> list = msslyyUserService.list();
        return Result.success(list);
    }

    @ApiOperation(value = "分页",notes = "")
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<MsslyyUser> query = Wrappers.<MsslyyUser>lambdaQuery().orderByDesc(MsslyyUser::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(MsslyyUser::getUserUsername, name);
        }
        IPage<MsslyyUser> page = msslyyUserService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

    @GetMapping("/findByUsername/{username}")
    public Result<?> findByUsername(@PathVariable String username) {
        LambdaQueryWrapper<MsslyyUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MsslyyUser::getUserUsername,username);
        return Result.success(msslyyUserService.getOne(queryWrapper));
    }

}
